﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace Lacrima.Framework.Infrastructure
{
    public static class FileUtils
    {
        /// <summary>
        /// 判断路径是否存在，如果不存在的话则创建该目录
        /// </summary>
        /// <param name="filePath"></param>
        public static void CreateDirectoryIfNotExist(string filePath)
        {
            string dir = filePath.Substring(0, filePath.LastIndexOf(@"\"));
            if (!Directory.Exists(dir))
            {
                Directory.CreateDirectory(dir);
            }
        }

        /// <summary>
        /// 根据文件路径名称计算文件MD5值
        /// 可能存在问题（比如不同目录下的同一个文件）
        /// 在网上搜索到相关问题之后考虑修正
        /// </summary>
        /// <param name="filePath">The file path.</param>
        /// <returns>System.String.</returns>
        public static string GetFileHashCode(string filePath)
        {
            return MD5Provider.GetFileHashCode(filePath);
        }

        /// <summary>
        /// 将字符串内容写入到文本文件
        /// </summary>
        /// <param name="filePath">文本文件路径</param>
        /// <param name="text">要写入的字符串内容</param>
        /// <param name="encoding">字符编码</param>
        public static void WriteToFile(string filePath, string text, string encoding = "utf-8")
        {
            try
            {
                if (System.IO.File.Exists(filePath))
                {
                    using (StreamWriter writer = new StreamWriter(filePath, false, Encoding.Default))
                    {
                        writer.WriteLine(text);
                        writer.Flush();
                        writer.Close();
                    }
                }
            }
            catch(Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Debug.WriteLine(ex.StackTrace);
                throw ex;
            }
        }

        /// <summary>
        /// 将DataTable中数据写入到CSV文件中
        /// </summary>
        /// <param name="dataTable">提供保存数据的DataTable</param>
        /// <param name="filePath">CSV的文件路径</param>
        public static void SaveCSV(DataTable dataTable, string filePath)
        {
            FileStream fileStream = new FileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
            StreamWriter streamWriter = new StreamWriter(fileStream, System.Text.Encoding.Default);
            string data = "";

            //写出列名称
            for (int i = 0; i < dataTable.Columns.Count; i++)
            {
                data += dataTable.Columns[i].ColumnName.ToString();
                if (i < dataTable.Columns.Count - 1)
                {
                    data += ",";
                }
            }
            streamWriter.WriteLine(data);

            //写出各行数据
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                data = "";
                for (int j = 0; j < dataTable.Columns.Count; j++)
                {
                    data += dataTable.Rows[i][j].ToString();
                    if (j < dataTable.Columns.Count - 1)
                    {
                        data += ",";
                    }
                }
                streamWriter.WriteLine(data);
            }

            streamWriter.Close();
            fileStream.Close();
        }

        public static void SaveToXml<T>(string filePath, object sourceObj, string xmlRootName)
        {
            Type type = sourceObj.GetType() ?? typeof(T);
            try
            {
                if (!string.IsNullOrWhiteSpace(filePath) && sourceObj != null)
                {
                    FileUtils.CreateDirectoryIfNotExist(filePath);
                    using (StreamWriter writer = new StreamWriter(filePath))
                    {
                        System.Xml.Serialization.XmlSerializer xmlSerializer = null;
                        if (string.IsNullOrWhiteSpace(xmlRootName))
                        {
                            xmlSerializer = new System.Xml.Serialization.XmlSerializer(type);
                        }
                        else
                        {
                            xmlSerializer = new System.Xml.Serialization.XmlSerializer(type, new XmlRootAttribute(xmlRootName));
                        }
                        xmlSerializer.Serialize(writer, sourceObj);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
